package com.just521.xinshoutong;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.feedback.UMFeedbackService;
import com.just521.xinshoutong.calendar.Activity_Calendar;
import com.just521.xinshoutong.calendar.CalendarView;
import com.just521.xinshoutong.common.CommonDefine;
import com.just521.xinshoutong.database.NoteDBCtrl;
import com.just521.xinshoutong.database.NoteDBCtrl.DBAccessListener;
import com.just521.xinshoutong.database.NoteDBCtrl.DBRequestParam;
import com.just521.xinshoutong.json.MainList_Summary;
import com.just521.xinshoutong.json.MainList_SummaryRec;
import com.just521.xinshoutong.json.TagList;
import com.just521.xinshoutong.json.TagList_Rec;
import com.just521.xinshoutong.listadapter.MainNoteListAdapter;
import com.just521.xinshoutong.listadapter.MainTagListAdapter;
import com.just521.xinshoutong.view.ToastFuncList;

public class Activity_main_notelist extends ActivityBase implements OnClickListener,OnGestureListener,OnTouchListener,
DBAccessListener{

	private GestureDetector detector;
	private ViewPager mPager;//页卡内容
	private List<View> listViews; // Tab页面列表
	byte[] mlock=new byte[0];
	int mdownposX;
	int mlastposX;
	int mlengthMove;
	ListView mNoteListView;
	ListView mNoteListView_todo;
	GridView mTagListView;
	
	LinearLayout mDragFrame;
	TextView mTagList;
	int mInitWidth;
	View mtitle;
	View mtool;
	
	ToastFuncList mtoastlist;
	
	Button mtaglistOp;
	
	int mlistStatus;
	NoteDBCtrl mdbctrl;
	MainNoteListAdapter<MainList_SummaryRec> madapter;
	List<MainList_SummaryRec> mlist;
	
	MainTagListAdapter<TagList_Rec> madapter_taglist;
	public static List<TagList_Rec> mlist_tag;
	boolean mbIsLongClick;
	int mdisplaywidth;
	int mdragrange;
	
	boolean mbProcessTouch;
	class ListScrollStatus{
		public static final int Init=0;
		public static final int MovingUp=1;
		public static final int MovingDown=2;
		public static final int Down=3;
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_notelist);

		mQuitListener=new QuitListener();
		mlist_tag=null;
		
		mdisplaywidth=getResources().getDisplayMetrics().widthPixels;
		mdragrange=(int)getResources().getDisplayMetrics().density*70;
		detector = new GestureDetector(this);
		
		mNoteListView=(ListView)findViewById(R.id.main_notelist);
		
		mtitle=findViewById(R.id.main_title);
		mtool=findViewById(R.id.main_tool);
//		mtaglistOp=(Button)findViewById(R.id.main_taglist_op);
//		mtaglistOp.setOnClickListener(this);
		
		mTagListView=(GridView)findViewById(R.id.main_taglist);
		
		mdbctrl=new NoteDBCtrl();
		DBRequestParam param=mdbctrl.getRequestParam();
		param.listener=this;
		param.task="getNoteSummaryList";
		mdbctrl.getNoteSummaryList_Local(param, 0, 50);
		madapter=new MainNoteListAdapter<MainList_SummaryRec>(this, new ArrayList<MainList_SummaryRec>(), null);
		
		
		madapter_taglist=new MainTagListAdapter<TagList_Rec>(this, new ArrayList<TagList_Rec>(), null);
		mTagListView.setAdapter(madapter_taglist);
//		mTagList=(TextView)findViewById(R.id.main_taglist);
		mDragFrame=(LinearLayout)findViewById(R.id.main_drag_frame);
		
		Button btn=(Button)findViewById(R.id.main_viewmode);
		btn.setOnClickListener(this);
		btn=(Button)findViewById(R.id.main_addnote);
		btn.setOnClickListener(this);
		btn=(Button)findViewById(R.id.main_tool_tags);
		btn.setOnClickListener(this);
		
		mtoastlist=(ToastFuncList)findViewById(R.id.toast_func_right);
		mtoastlist.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				if(arg2==0 ){
					
				}else if(arg2==1){
					
				}
			}
		});
		mtoastlist.setListData(new String[]{getstring(R.string.main_view_mode_list),getstring(R.string.main_view_mode_calendar)});
		
		initPager();
	}
	void initPager(){
//		mPager = (ViewPager) findViewById(R.id.vPager);
//		LayoutInflater mInflater = getLayoutInflater();
//		listViews = new ArrayList<View>();
//		mNoteListView=(ListView)mInflater.inflate(R.layout.main_listlayout, null);
		mNoteListView.setOnTouchListener(this);
		mNoteListView.setOnItemLongClickListener(new OnItemLongClickListener() {
			public boolean onItemLongClick(AdapterView<?> parent, View view,
				    int position, long id) {
//				mbIsLongClick=true;   
				   
				return true;
			}  
		});
		mNoteListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
				    int position, long id) {
				MainList_SummaryRec rec=(MainList_SummaryRec)madapter.getItem(position);
				Intent it=new Intent(Activity_main_notelist.this,Activity_note.class);
				it.putExtra("summary", rec);
				startActivity(it);
			}  
		});
		mNoteListView.setAdapter(madapter);
//		listViews.add(mNoteListView);
//		
//		mNoteListView_todo=(ListView)mInflater.inflate(R.layout.main_listlayout, null);
//		mNoteListView_todo.setOnTouchListener(this);
//		mNoteListView_todo.setOnItemLongClickListener(new OnItemLongClickListener() {
//			public boolean onItemLongClick(AdapterView<?> parent, View view,
//				    int position, long id) {
//				   
//				return true;
//			}  
//		});
//		mNoteListView_todo.setOnItemClickListener(new OnItemClickListener() {
//			@Override
//			public void onItemClick(AdapterView<?> parent, View view,
//				    int position, long id) {
//				MainList_SummaryRec rec=(MainList_SummaryRec)madapter.getItem(position);
//				Intent it=new Intent(Activity_main_notelist.this,Activity_note.class);
//				it.putExtra("summary", rec);
//				startActivity(it);
//			}  
//		});
//		mNoteListView_todo.setAdapter(madapter);
//		listViews.add(mNoteListView_todo);
		
//		CalendarView calView=new CalendarView(this);
//		calView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
//		calView.setActivity(this);
//		listViews.add(calView);
	
//		mPager.setAdapter(new MyPagerAdapter(listViews));
//		mPager.setCurrentItem(0);
//		mPager.setOnPageChangeListener(new MyOnPageChangeListener());
	}
	
	protected void onDestroy() {
		super.onDestroy();
		
	}
	protected void onResume() {
		super.onResume();
		
	}
	@Override
	public void onClick(View v) {
		switch(v.getId()){
//		case R.id.main_setting:
//			do_main_setting();
//			break;
		case R.id.main_tool_tags:
			if(mlistStatus==ListScrollStatus.Init){
				showTagsList();
			}else{
				hideTagsList();
			}
			break;
		case R.id.main_viewmode:
//			mtoastlist.showanimation();
			startActivity(new Intent(this,Activity_Calendar.class));
			break;	
		case R.id.main_addnote:
			startActivity(new Intent(this,Activity_note.class));
			break;
		default:
			break;
		}	
	}
	void showTagsList(){
		int top =mDragFrame.getTop();
		int bottom =mDragFrame.getBottom();
		mDragFrame.layout(mInitWidth, top, mdisplaywidth, bottom);
		mlistStatus=ListScrollStatus.Down;
	}
	void hideTagsList(){
		int top =mDragFrame.getTop();
		int bottom =mDragFrame.getBottom();
		mDragFrame.layout(0, top, mdisplaywidth, bottom);
		mlistStatus=ListScrollStatus.Init;
	}
	void op_taglist(){
		if(mTagListView.getVisibility()==View.GONE){
			mtaglistOp.setText("隐藏标签列表");
			mTagListView.setVisibility(View.VISIBLE);
		}else{
			mtaglistOp.setText("显示标签列表");
			mTagListView.setVisibility(View.GONE);
		}
	}
	void do_main_setting(){
	
	}

	void do_main_region(){
	
	}

	void do_main_nearby(){
	
	}

	void do_main_feedback(){
		UMFeedbackService.openUmengFeedbackSDK(this);
	}
	public boolean dispatchTouchEvent (MotionEvent event){
		mtoastlist.processHit(event);
		boolean bret=false;
		Rect rect=new Rect();
		do{
			
			mDragFrame.getHitRect(rect);
			if(event.getX()<rect.left ){
				break;
			}
			mtitle.getHitRect(rect);
			if(event.getY()<rect.bottom){
				break;
			}
			mtool.getHitRect(rect);
			if(event.getY()>rect.top){
				break;
			}
			int left=0;
			int right = 0;
			int top =mDragFrame.getTop();
			int bottom =mDragFrame.getBottom();
			mInitWidth=mTagListView.getWidth();
			int action=event.getAction();  
			switch(action){  
			case MotionEvent.ACTION_DOWN:
				int tempx=(int)event.getX();
				if(tempx>mdragrange && mlistStatus==ListScrollStatus.Init){
					break;
				}else if(tempx>(mdragrange+mInitWidth) && mlistStatus==ListScrollStatus.Down){
					break;
				}
				bret=true;
				mdownposX=tempx;
				mlastposX=mdownposX;
				
//        	Log.i("debug_ld", "down pos:"+mdownposX);
				break;  
				
			case MotionEvent.ACTION_MOVE:
				if(mdownposX==0){
					break;
				}
				int curX=(int)event.getX();
				mlengthMove=mlastposX-mdownposX;
				
				if(mlengthMove>CommonDefine.DRAG_LIST_LENGTH){
					if(mlistStatus==ListScrollStatus.Down){
						break;
					}
					bret=true;
					mlistStatus=ListScrollStatus.MovingDown;
					if(curX<mlastposX){
						break;
					}
					int curmove=curX-mlastposX;
//        		left = mDragFrame.getLeft()+curmove;
					left=mlengthMove;
					right = left+mdisplaywidth;
					mDragFrame.layout(left, top, right, bottom);
//        		Log.i("debug_ld", "position move down" +"  " +curX+", " +mlastposX+", " +  mlengthMove+ ", " + left +", " + top  + ", " + right  + ", " + bottom );
				}
				if(mlengthMove<-CommonDefine.DRAG_LIST_LENGTH){
					if(mlistStatus==ListScrollStatus.Init){
						break;
					}
					bret=true;
					mlistStatus=ListScrollStatus.MovingUp;
					if(curX>mlastposX){
						break;
					}
					int curmove=curX-mlastposX;
//        		left = mDragFrame.getLeft()+curmove;
					left=mInitWidth+mlengthMove;
					right = left+mdisplaywidth;
					mDragFrame.layout(left, top, right, bottom);
//        		Log.i("debug_ld", "position move up" +mlengthMove+ ", " + left +", " + top  + ", " + right  + ", " + bottom );
				}
				mlastposX=curX;
				break;  
			case MotionEvent.ACTION_UP:  
				if(mlistStatus!=ListScrollStatus.MovingUp && mlistStatus!=ListScrollStatus.MovingDown){
					mdownposX=0;
					mlengthMove=0;
					mlastposX=0;
					break;
				}
				bret=true;
				int width=mTagListView.getWidth();
				boolean bisLeft=false;
				if(Math.abs(mlengthMove)>(width/2)){
					if(mlengthMove>0){
						
					}else{
						bisLeft=true;
					}
					
				}else{
					if(mlengthMove>0){
						bisLeft=true;
					}else{
						
					}
				}
				if(bisLeft){
					mlistStatus=ListScrollStatus.Init;
					//to top
					left = 0;
					right = mdisplaywidth;
				}else{
					//to bottom
					mlistStatus=ListScrollStatus.Down;
					left = width;
					right = mdisplaywidth;
				}
				mDragFrame.layout(left, top, right, bottom);
//    		Log.i("debug_ld", "position return" + left +", " + top  + ", " + right  + ", " + bottom );
				mdownposX=0;
				mlengthMove=0;
				mlastposX=0;
				break;                
			}  
		}while(false);
        if(!bret){
        	bret=super.dispatchTouchEvent(event);
        }
		return bret;
	}
	public boolean onTouch(View arg0, MotionEvent event) {
		mbProcessTouch=true;
        return false;
    }  
		
	
	public boolean onDown(MotionEvent e) {
		return false;
	}

	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		int a=3;
		return false;
	}

	public void onLongPress(MotionEvent e) {
		
	}

	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		return false;
	}

	public void onShowPress(MotionEvent e) {
		
	}

	public boolean onSingleTapUp(MotionEvent e) {
		return false;
	}
	
	public void onDBSuccess(DBRequestParam param){
		if(param.task.equals("getNoteSummaryList")){
			
			MainList_Summary summarylist=JSON.parseObject(param.rstjson,MainList_Summary.class);
			mlist=summarylist.getSummarylist();
			madapter.UpdateList(mlist);
			
			if(mlist_tag==null){
				Log.v("debug_ld", "getTagList");
				DBRequestParam paramre=mdbctrl.getRequestParam();
				paramre.listener=this;
				paramre.task="getTagList";
				mdbctrl.getTagList_Local(paramre);
			}
		}else if(param.task.equals("getTagList")){
			if(param.rstjson==null){
				mlist_tag=new ArrayList<TagList_Rec>();
			}else{
				
				mlist_tag=JSON.parseArray(param.rstjson, TagList_Rec.class);
				Log.v("debug_ld", "getTagList:"+mlist_tag.size());
			}
			madapter_taglist.UpdateList(mlist_tag);
		}
		
	}
	public void onDBError(DBRequestParam param){
		Log.v("debug_ld", "err:"+param.task);
	}
	
	public class MyPagerAdapter extends PagerAdapter {
		public List<View> mListViews;

		public MyPagerAdapter(List<View> mListViews) {
			this.mListViews = mListViews;
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView(mListViews.get(arg1));
		}

		@Override
		public void finishUpdate(View arg0) {
		}

		@Override
		public int getCount() {
			return mListViews.size();
		}

		@Override
		public Object instantiateItem(View arg0, int arg1) {
			((ViewPager) arg0).addView(mListViews.get(arg1), 0);
			return mListViews.get(arg1);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == (arg1);
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {
		}
	}

	/**
	 * 头标点击监听
	 */
	public class MyOnClickListener implements View.OnClickListener {
		private int index = 0;

		public MyOnClickListener(int i) {
			index = i;
		}

		@Override
		public void onClick(View v) {
			mPager.setCurrentItem(index);
		}
	};

	/**
	 * 页卡切换监听
	 */
	public class MyOnPageChangeListener implements OnPageChangeListener {

		@Override
		public void onPageSelected(int arg0) {
			Animation animation = null;
			switch (arg0) {
			case 0:
				
				break;
			case 1:
				
				break;
			case 2:
				
				break;
			}
			
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}
		
	}
	
	
	
	
	
	

}

